home *** CD-ROM | disk | FTP | other *** search
-
- // dispatch.cpp
- // joseph mcdermott 73740,3461 8 oct 1991
- // illustration only !!!!
- // safety not guaranteed !!!!!
- //
- // This program illustrates Borland's dynamic dispatch by value
- // --------------------------------------------------------
- // NOTE: compile with large model and far virtual tables
- // If you chamnge these parameters, you must recompile 'dd.asm'.
- // The code is based on 'windobj.cpp' and 'dd.asm'
- // I have removed all dependencies on Windows 3.0 and OWL.
- // This is a DOS program.
- // ---------------------------------------------------------
- #include <stdio.h>
-
- #define getVptr(thisPtr) (*(void far **)(thisPtr))
- #define WORD unsigned int
-
- // now define dispatch indexes
- #define INDX_A 11
- #define INDX_B 12
- #define INDX_C 13
- #define INDX_D 14
-
- class DispatchClass
- {
- public:
- void send(WORD, char *);
- virtual void method_a(char * ) = [INDX_A]; // [INDX_A] is the dispatch index
- virtual void method_b(char * ) = [INDX_B];
- virtual void method_c(char * ) = [INDX_C];
- virtual void method_d(char * ) = [INDX_D];
-
- };
-
- // the following typedef must match the virtual functions to be called
- // which should all have the same prototype pattern
- //
- // there is nothing special about '(char *)'
- // any set of variables can be passed, but the prototypes should
- // be consistent
-
- typedef void (DispatchClass::* far ClassMFP) (char *);
-
- // 'Ddispatch' is in an assembly routine essentially identical to
- // 'dd.asm' in borland's owl source directory. This function searches
- // the virtual table for a matching index. It returns a function pointer
- // if a match is found, zero otherwize. The compiler loads the indexes
- // into the virtual table (NOT a standard C++ feature !!)
-
- extern "C" ClassMFP Ddispatch(void far *vptr, WORD Dval);
-
-
- // 'send()' takes the dispatch index and calls the appropriate
- // virtual function if it exists.
-
- void DispatchClass::send(WORD Dval, char *chr)
- {
- ClassMFP MFP;
-
- // get method pointer by calling assembly routine
- // returns 0 if none found
- MFP = Ddispatch(getVptr(this), Dval);
-
- if (MFP)
- (this->*MFP)(chr); // dispatch here !!!
- else
- /* default handling */
- printf("No method found for value: %d \n", Dval);
- }
-
- // a set of virtual functions Method_a to Method_d
- // that will receive the dynamic dispatch
-
- void DispatchClass::method_a(char *s)
- {
- printf("Method_a: %s\n", s);
- }
-
- void DispatchClass::method_b(char *s)
- {
- printf("Method_b: %s\n", s);
- }
-
- void DispatchClass::method_c(char *s)
- {
- printf("Method_c: %s\n", s);
- }
-
-
- void DispatchClass::method_d(char *s)
- {
- printf("Method_d: %s\n", s);
- }
-
- main()
- {
- DispatchClass DC;
-
- DC.send(INDX_A, "send to a");
- DC.send(INDX_B, "send to b");
- DC.send(INDX_C, "send to c");
- DC.send(INDX_D, "send to d");
-
- DC.send(99, "send to ???"); // no index for this one
-
-
- }